import axios from "axios"
import { TOKEN } from "@/constants"
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"

// 创建 axios 实例
const createClient = (config?: AxiosRequestConfig): AxiosInstance => {
  const client = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
    timeout: 10000,
    ...config
  })

  // 请求拦截器
  client.interceptors.request.use(
    (config) => {
      // 在这里可以添加认证token等
      const token = localStorage.getItem(TOKEN)
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  client.interceptors.response.use(
    (response: AxiosResponse) => {
      // 处理业务错误
      if (response.data.code !== 1) {
        throw new Error(response.data.message || response.data.msg || "请求失败")
      }

      return response.data
    },
    (error: AxiosError) => {
      // 统一错误处理
      if (error.response) {
        // 根据 HTTP 状态码处理不同错误
        switch (error.response.status) {
          case 401:
            // 不是获取用户信息接口或者登录页面，则跳转到登录页面
            if (!error.config?.url?.includes("/User/Get") && !window.location.pathname.includes("/login")) {
              localStorage.removeItem(TOKEN)
              window.location.href = `/login?redirect=${window.location.pathname}`
            }
            break
          case 403:
            // 处理禁止访问
            break
          case 500:
            // 处理服务器错误
            break
          default:
            // 处理其他状态码
            break
        }
      }

      return Promise.reject(error)
    }
  )

  return client
}

const apiClient = createClient()

export { createClient, apiClient }
